package com.fengye.security.custom.handler;

import com.alibaba.fastjson.JSON;
import com.fengye.common.constants.AppHttpCodeEnum;
import com.fengye.common.domain.ResponseResult;
import com.fengye.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sunlei
 * @version 1.0
 * @date 2023/9/11 21:25:09
 * @description 认证失败处理器，该接口则是在用户尚未通过身份验证（即未登录）的情况下，尝试访问需要认证的资源时被调用的，
 * 即当 Spring Security 的 ExceptionTranslationFilter 捕获到 AuthenticationException 异常时，它会调用 AuthenticationEntryPoint 来处理这种情况。
 */
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
        log.error("认证失败：{}", authException.getMessage());
        // 处理异常
        ResponseResult<Object> result = null;
        if (authException instanceof BadCredentialsException) {
            result = ResponseResult.fail(AppHttpCodeEnum.USERNAME_OR_PWD_ERROR);
        } else if (authException instanceof InsufficientAuthenticationException) {
            result = ResponseResult.fail(AppHttpCodeEnum.UNAUTHORIZED);
        } else {
            result = ResponseResult.fail(AppHttpCodeEnum.UNAUTHORIZED).setMessage(authException.getMessage());
        }
        ServletUtils.renderString(response, JSON.toJSONString(result));
    }
}
